package com.zdsoft.p2p.websocket.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import com.google.gson.GsonBuilder;
import com.zdsoft.p2p.websocket.domain.Message;
import com.zdsoft.p2p.websocket.domain.User;
import com.zdsoft.p2p.websocket.socket.MyWebSocketHandler;
import com.zdsoft.rock.common.controller.AbstractController;

@Controller
@RequestMapping("/msg")
public class MsgController extends AbstractController{

	@Resource
	MyWebSocketHandler handler;

	Map<Long, User> users = new HashMap<Long, User>();

	// 模拟一些数据
	@ModelAttribute
	public void setReqAndRes() {
		User u1 = new User();
		u1.setId(1L);
		u1.setName("张三");
		users.put(u1.getId(), u1);

		User u2 = new User();
		u2.setId(2L);
		u2.setName("李四");
		users.put(u2.getId(), u2);
	}
	/**
	 * 进入websocket工程
	 * @return
	 */
	@RequestMapping("/index.do")
	public String index(){
		return "websocket/index";
	}
	
	//进入登陆页面
	@RequestMapping(value = "/login.do",method=RequestMethod.GET)
	public ModelAndView login(){
		logger.debug("进入登陆界面");
		return new ModelAndView("websocket/login");
	}
	
	// 用户登录
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public ModelAndView doLogin(User user, HttpSession session) {
		logger.debug("登陆提交");
		session.setAttribute("uid", user.getId());
		session.setAttribute("name", users.get(user.getId()).getName());
		return new ModelAndView("websocket/talk");
	}

	// 跳转到交谈聊天页面
	@RequestMapping(value = "/talk.do", method = RequestMethod.GET)
	public ModelAndView talk() {
		logger.debug("跳转到交谈聊天页面");
		return new ModelAndView("websocket/talk");
	}

	// 跳转到发布广播页面
	@RequestMapping(value = "/broadcast.do", method = RequestMethod.GET)
	public ModelAndView broadcast() {
		logger.debug("跳转到发布广播页面");
		return new ModelAndView("websocket/broadcast");
	}

	// 发布系统广播（群发）
	@ResponseBody
	@RequestMapping(value = "/broadcast.do", method = RequestMethod.POST)
	public void broadcast(String text) throws IOException {
		logger.debug("发布系统广播（群发）");
		Message msg = new Message();
		msg.setDate(new Date());
		msg.setFrom(-1L);
		msg.setFromName("系统广播");
		msg.setTo(0L);
		msg.setText(text);
		handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
	}

}